package com.knowledgegraph.controller;

import com.knowledgegraph.common.Result;
import com.knowledgegraph.entity.User;
import com.knowledgegraph.service.UserService;
import com.knowledgegraph.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户控制器
 * 
 * @author system
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    private final JwtUtil jwtUtil;

    /**
     * 获取当前用户信息
     */
    @PostMapping("/profile")
    public Result<User> getCurrentUser(HttpServletRequest request) {
        try {
            // 从请求头获取token
            String authHeader = request.getHeader(jwtUtil.getHeader());
            String token = jwtUtil.getTokenFromHeader(authHeader);
            
            if (token == null) {
                return Result.error(401, "未提供认证令牌");
            }
            
            // 验证token
            if (!jwtUtil.validateToken(token)) {
                return Result.error(401, "认证令牌无效或已过期");
            }
            
            // 获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                return Result.error(401, "无法从令牌中获取用户信息");
            }
            
            // 查询用户信息
            User user = userService.getById(userId);
            if (user == null) {
                return Result.error(404, "用户不存在");
            }
            
            // 清除敏感信息
            user.setPassword(null);
            
            return Result.success("获取用户信息成功", user);
            
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return Result.error(500, "获取用户信息失败");
        }
    }

    /**
     * 更新用户信息
     */
    @PostMapping("/update-profile")
    public Result<User> updateProfile(@RequestBody User userInfo, HttpServletRequest request) {
        try {
            // 从请求头获取token
            String authHeader = request.getHeader(jwtUtil.getHeader());
            String token = jwtUtil.getTokenFromHeader(authHeader);
            
            if (token == null || !jwtUtil.validateToken(token)) {
                return Result.error(401, "认证失败");
            }
            
            // 获取当前用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                return Result.error(401, "无法获取用户信息");
            }
            
            // 设置用户ID，防止修改其他用户信息
            userInfo.setId(userId);
            
            // 更新用户信息
            boolean updated = userService.updateUser(userInfo);
            if (!updated) {
                return Result.error(500, "更新用户信息失败");
            }
            
            // 获取更新后的用户信息
            User updatedUser = userService.getById(userId);
            if (updatedUser != null) {
                updatedUser.setPassword(null);
            }
            
            return Result.success("更新用户信息成功", updatedUser);
            
        } catch (Exception e) {
            log.error("更新用户信息失败", e);
            return Result.error(500, "更新用户信息失败");
        }
    }
}